<template>
  <!-- 订单筛选门店 -->
  <div :class="$style.filtterOrder">
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item
          prop="sourceSystem"
          label="来源系统"
          :rules="[
            { required: true, message: '请选择来源系统', trigger: ['blur', 'change'] }
          ]"
        >
          <el-select v-model="formData.sourceSystem" filterable clearable placeholder="请选择来源系统">
            <el-option
              v-for="list in sourceList"
              :key="list.code"
              :value="list.code"
              :label="list.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="platformCode" label="电商平台">
          <!--  url="/call-center/api/v1/mscInfo/b2c/platform/page" -->
          <SearchSelectPicker
            url="/select-service/api/v1/eco/platform/page"
            :params="{query:null,type:0}"
            placeholder="请选择所电商平台"
            value-name="code"
            lable-name="name"
            :value.sync="formData.platformCode"
            multiple
            @selectChange="platformCodeChange"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="storeCode" label="电商店铺">
          <!-- url="/call-center/api/v1/mscInfo/b2c/store/page" -->
          <SearchSelectPicker
            ref="storeSelect"
            url="/select-service/api/v1/eco/shop/page"
            placeholder="请选择所电商店铺"
            :params="{query:{platformCode:{value: formData.platformCode, operator: 'IN'}},type:0}"
            must-pid
            value-name="code"
            lable-name="name"
            multiple
            :parent-id="formData.platformCode"
            :value.sync="formData.storeCode"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="serviceCode" label="服务商">
          <SearchSelectPicker
            ref="serviceSelect"
            url="/call-center/api/v1/mscInfo/dealer/page"
            placeholder="请选择服务商"
            :params="{query:null,type:1}"
            value-name="code"
            lable-name="name"
            custom-name="name"
            :value.sync="formData.serviceCode"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="createTime" label="送装完成时间">
          <el-date-picker
            v-model="formData.createTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            opt
            :limite="new Date()"
            operator=">"
          />
        </el-form-item>
        <el-form-item prop="orderDate" label="购买时间">
          <el-date-picker
            v-model="formData.orderDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            opt
            :limite="new Date()"
            operator=">"
          />
        </el-form-item>
        <el-form-item prop="orderAmount" label="购买金额">
          <el-input v-model="formData.orderAmount[0]" style="width:46%" clearable number />
          <el-input v-model="formData.orderAmount[1]" style="width:46%" clearable number />
        </el-form-item>
        <el-form-item prop="orderNum" label="抽取订单量">
          <el-input v-model.trim="formData.orderNum" v-number-input clearable />
        </el-form-item>
        <el-form-item>
          <Button @click="$refs.form.resetFields()">重置</Button>
          <Button type="primary" @click="queryHandle">查询</Button>
        </el-form-item>
      </el-form>
    </FormContainer>
    <div class="button-container" style="padding-top:0">
      <Button type="primary" :loading="loading" @click="confrimAdd">确认新增</Button>
      <!-- <Button type="danger" @click="delet">删除</Button> -->
      <i></i>
      <Button type="primary" @click="next">下一步</Button>
    </div>
    <table-box
      ref="table"
      :class="'checkbox_table'+(paginationHidden?' hidden_page':'') "
      no-request
      :other-filters="otherFilters"
      :selected-arry="selectedAry"
      :table-config="tableConfig"
      :other-raw="otherRaw"
      @data-change="getTableData"
      @selection-change="selectionChange"
    >
      <el-table-column slot="before" type="selection" width="50" align="center"></el-table-column>
    </table-box>
    <div v-if="paginationHidden" :class="$style.total">共<span>{{ total }}</span>条</div>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { filtersRaw, parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'
import { callBackTaskAddBatchObj } from '@/api/callBackTask'

export default {
  name: 'FiltOrdForClient',
  components: {
    FormContainer,
    Button,
    SearchSelectPicker
  },
  data() {
    const validatorOrederNum = (r, v, c) => {
      if (v !== '' && v <= 0) {
        c(new Error('订单抽取量不能小于等于零'))
      } else {
        c()
      }
    }
    return {
      loading: false,
      formData: {
        sourceSystem: '', // 来源系统
        platformCode: [],
        storeCode: [],
        serviceCode: '',
        createTime: [],
        orderDate: [],
        orderNum: '',
        orderAmount: []
      },
      // sourceList: [{ code: '0', name: 'B2C' }, { code: '1', name: 'ECO' }],
      paginationHidden: false, // 分页隐藏
      addSuccess: false,
      formRules: {
        orderNum: [{ validator: validatorOrederNum, trigger: 'change' }]
      },
      otherFilters: [],
      otherRaw: {},
      tableConfig: {
        interfacePath: '/call-center/api/v1/callBackCommerceOrder/page',
        sort: 'orderTime',
        order: 'desc',
        pageFlag: true,
        hideFuncBar: true,
        tablePage: [10, 20, 30, 50, 80, 100, 200, 300, 500, 1000, 2000, 3000],
        // 表格字段动态配置
        setting: [
          {
            prop: 'orderCode',
            label: '订单编号'
          },
          {
            prop: 'platformName',
            label: '平台名称'
          },
          {
            prop: 'storeName',
            label: '店铺名称'
          },
          {
            prop: 'serviceName',
            label: '服务商名称'
          },
          {
            prop: 'customerName',
            label: '顾客姓名'
          },
          {
            prop: 'contactNumber',
            label: '联系电话1'
          },
          {
            prop: 'contactNumberBak',
            label: '联系电话2'
          },
          {
            prop: 'orderAmount',
            label: '购买金额'
          }
        ]
      },
      selectedAry: [],
      addData: {
        visitPeople: ''
      },
      total: 0
    }
  },
  computed: {
    ...mapState({
      taskId: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].basic.id : ''
      },
      step: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].step : 1
      },
      objectMethod: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].basic.objectMethod : ''
      }
    }),
    sourceList() {
      return this.objectMethod === 1 ? [{ code: '1', name: 'ECO' }] : [{ code: '0', name: 'B2C' }, { code: '1', name: 'ECO' }]
    }
  },
  methods: {
    ...mapMutations({
      SET_STEP: 'taskForm/SET_STEP'
    }),
    // 查询
    queryHandle() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const list = []
          this.tableConfig.interfacePath = `/call-center/api/v1/callBackCommerceOrder/page`
          // ?sourceSystem=${this.formData.sourceSystem}
          const filters = JSON.parse(JSON.stringify(this.formData))
          // delete filters.sourceSystem

          for (const [key, value] of Object.entries(filters)) {
            if (value === '' || value === undefined || value === null || key === 'orderNum') {
              continue
            }
            if (Array.isArray(value)) {
              if (value.length <= 0) {
                continue
              }
              switch (key) {
                case 'orderDate':
                  list.push(filtersRaw(key, parseTime(value[0], '{y}-{m}-{d}'), '>='))
                  list.push(filtersRaw(key, parseTime(value[1], '{y}-{m}-{d}'), '<='))
                  break
                case 'createTime':
                  list.push(filtersRaw(key, parseTime(value[0], '{y}-{m}-{d} 00:00:00'), '>='))
                  list.push(filtersRaw(key, parseTime(value[1], '{y}-{m}-{d} 23:59:59'), '<='))
                  break
                case 'orderAmount':
                  if (value[0] !== '') {
                    list.push(filtersRaw(key, value[0], '>='))
                  }
                  if (value[1] !== '') {
                    list.push(filtersRaw(key, value[1], '<='))
                  }
                  break
                default:
                  list.push(filtersRaw(key, `[${value.join(',')}]`, 'in'))
                  break
              }
            } else {
              list.push(filtersRaw(key, value, '='))
            }
          }
          this.otherFilters = list
          const otherRaw = {}
          if (this.formData.orderNum > 0) {
            otherRaw.orderNum = this.formData.orderNum
          }
          this.otherRaw = otherRaw
          this.refresh()
        }
      })
    },
    // 确认新增
    confrimAdd() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请至少选择一条数据')
      }
      this.loading = true
      this.selectedAry.forEach(e => {
        e.taskId = this.taskId
        e.serviceProviderName = e.serviceName
        e.serviceProviderCode = e.serviceCode
        e.shopName = e.storeName
        e.shopCode = e.storeCode
        e.customerPhone = e.contactNumber
      })
      callBackTaskAddBatchObj({
        objectMethod: 1,
        callBackObjectOnlineDTOList: this.selectedAry
      })
        .then(res => {
          this.loading = false
          if (res.success === 1) {
            this.addSuccess = true
            this.$message.success('任务对象新增成功')
            // this.refresh()
          }
        })
        .catch(er => {
          this.loading = false
        })
    },
    // 删除
    delet() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请选择要删除的数据')
      }
      this.$msgbox({
        title: '确认删除',
        showCancelButton: true,
        type: 'warning',
        message: '确定删除所选择任务？'
      })
        .then(() => {
          this.refresh('onPage')
        })
        .catch(e => e)
    },
    next() {
      if (!this.addSuccess) {
        return this.$message.info('请先新增任务对象')
      }
      this.SET_STEP({ id: this.$route.query.id, step: this.step + 1 })
    },
    refresh(type) {
      this.$refs.table.$children.forEach(e => {
        if (
          e.$el.className &&
          e.$el.className.indexOf('pagination-container') > -1
        ) {
          if (this.formData.orderNum) {
            e.params.rows = parseInt(this.formData.orderNum)
          } else {
            e.params.rows = e.pageSizes[0]
          }
        }
      })
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    selectionChange(val) {
      this.selectedAry = val
    },
    getTableData(res) {
      this.paginationHidden = !!this.formData.orderNum
      this.total = res.data.records.length
    },
    // 电商平台变化
    platformCodeChange() {
      this.$set(this.formData, 'storeCode', '')
    }
  }
}
</script>
<style lang='scss' module>
.filtterOrder{
  & tr{
    background-color: white !important;
  }
  .total{
    padding: 10px;
    text-align: right;
    &>span{
      color: #16bc83;
      padding: 0 2px;
    }
  }
}
</style>
